package client;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import master.StretchBox;

public class Rechner extends JPanel {
    private static final long serialVersionUID = 1L;
	private boolean taken;
	private Timer refreshTimer;
	private Client client;
	private JLabel moneyLabel = new JLabel("");

    public Rechner(Client client) {
    	addAutoRefresh();
    	this.setLayout(new GridLayout(1,1));
    	this.add(new StretchBox(moneyLabel));
    	moneyLabel.setOpaque(false);
    	moneyLabel.setFont(new Font("Arial",Font.BOLD,30));
    	setClient(client);
    }
    
    private void setClient(Client client) {
		this.client=client;
	}
    
    public Client getClient() {
    	return this.client;
    }

	public void setTaken(boolean taken) {
    	this.taken=taken;
    	if (taken) {
    		setBackground(Color.RED);
    	}else{
    		setBackground(Color.GREEN);
    	}
    }
    
    public boolean isTaken() {
    	return taken;
    }
    
    private void addAutoRefresh() {
		this.refreshTimer = new Timer(50, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refresh();
			}
		});
		refreshTimer.start();
	}

	protected void refresh() {
		if (isTaken()) {
			try {
				moneyLabel .setText(getClient().getServer().getMoney(3));
			} catch (RemoteException e) {				
				e.printStackTrace();
			}
		}else{
			moneyLabel.setText("FREI");
		}
	}

}
